package test;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.concurrent.ScheduledExecutorService;

public class ClientMqtt {
    public static final String HOST = "tcp://wblink.tpddns.cn:8083";	//作为服务器使用（收集客户端发送的消息）
    public static final String TOPIC = "testtopic/#";	//定义消息的主题，客户端接收消息的根据
    private static final String clientid = "mqttjs_0dccb8f1c5";
    private MqttClient client;
    private MqttConnectOptions options;
    private String userName = "admin";
    private String passWord = "public";

    private ScheduledExecutorService scheduler;

    private void start() {
        try {
            client = new MqttClient(HOST, clientid, new MemoryPersistence());
            options = new MqttConnectOptions();
            options.setCleanSession(false);
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(20);

            client.setCallback(new PushCallback());
            MqttTopic topic = client.getTopic(TOPIC);
            options.setWill(topic, "close".getBytes(), 2, true);
            client.connect(options);
            int[] Qos  = {1};
            String[] topic1 = {TOPIC};
            client.subscribe(topic1, Qos);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws MqttException {
        ClientMqtt client = new ClientMqtt();
        client.start();
    }

}
